const axios = require('axios');

class LarkClient {
  constructor(config) {
    this.config = config;
    this.baseUrl = 'https://open.feishu.cn/open-apis';
    
    // 创建axios实例
    this.client = axios.create({
      baseURL: this.baseUrl,
      timeout: 30000,
      headers: {
        'Content-Type': 'application/json',
        'charset': 'utf-8'
      }
    });

    // 添加请求拦截器
    this.client.interceptors.request.use((config) => {
      if (this.config.userAccessToken) {
        config.headers.Authorization = `Bearer ${this.config.userAccessToken}`;
      }
      return config;
    });

    // 添加响应拦截器
    this.client.interceptors.response.use(
      response => response,
      error => {
        console.error('API请求错误:', error.response?.data || error.message);
        return Promise.reject(error);
      }
    );
  }

  /**
   * 获取用户"我的空间"根目录
   * @returns {Promise<Object>}
   */
  async getRootFolder() {
    const response = await this.client.get('/drive/explorer/v2/root_folder/meta');
    return response.data.data;
  }

  /**
   * 获取文件夹中的文件列表
   * @param {string} folderToken 文件夹token
   * @returns {Promise<Object>}
   */
  async getFolderChildren(folderToken) {
    const response = await this.client.get(`/drive/explorer/v2/folder/${folderToken}/children`);
    return response.data.data;
  }

  /**
   * 创建文档导出任务
   * @param {string} documentToken 文档token
   * @param {string} exportType 导出类型 (docx, markdown, pdf)
   * @returns {Promise<Object>}
   */
  async createExportTask(documentToken, exportType) {
    const response = await this.client.post('/drive/v1/export_tasks', {
      token: documentToken,
      type: 'docx', // 文档类型，目前只支持docx
      export_type: exportType
    });
    return response.data.data;
  }

  /**
   * 查询导出任务结果
   * @param {string} ticket 导出任务ticket
   * @returns {Promise<Object>}
   */
  async getExportTaskResult(ticket) {
    const response = await this.client.get(`/drive/v1/export_tasks/${ticket}`);
    return response.data.data;
  }

  /**
   * 下载导出的文件
   * @param {string} fileToken 文件token
   * @param {string} filePath 保存路径
   * @returns {Promise<void>}
   */
  async downloadExportedFile(fileToken, filePath) {
    const response = await this.client.get(`/drive/v1/export_tasks/file/${fileToken}/download`, {
      responseType: 'stream'
    });
    
    const writer = require('fs').createWriteStream(filePath);
    response.data.pipe(writer);
    
    return new Promise((resolve, reject) => {
      writer.on('finish', resolve);
      writer.on('error', reject);
    });
  }

  /**
   * 获取知识库列表
   * @returns {Promise<Object>}
   */
  async getWikiSpaces() {
    const response = await this.client.get('/wiki/v2/spaces');
    return response.data.data;
  }

  /**
   * 获取知识库中的文件列表
   * @param {string} spaceId 知识库ID
   * @returns {Promise<Object>}
   */
  async getWikiPages(spaceId) {
    const response = await this.client.get(`/wiki/v2/spaces/${spaceId}/nodes`);
    return response.data.data;
  }
}

module.exports = {
  LarkClient
};